package SampeDemo;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

public class SampeDemo {
    private JPanel panel = new JPanel();
    private JComboBox cmb = new JComboBox(); //创建一个下拉列表
    private JLabel label = new JLabel("添加新星座: ");
    private JLabel showInfo = new JLabel();  //用于显示信息
    private JTextField jtf = new JTextField(16);  //用于输入信息
    private JButton buttonAdd = new JButton("新增");
    private JButton buttonDel = new JButton("删除");

    public SampeDemo()
    {
        JFrame frame = new JFrame("请选择你的星座");
        cmb.addItem("--请选择--");
        cmb.addItem("狮子座");
        cmb.addItem("双子座");
        cmb.addItem("水瓶座");
        panel.add(cmb); //下拉列表
        panel.add(label);  //标签
        panel.add(jtf);  //文本框
        panel.add(buttonAdd);  //
        panel.add(buttonDel);
        frame.add(panel);
        buttonAdd.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String command = e.getActionCommand(); //得到监视的数据
                if(jtf.getText().length() != 0)
                {
                    cmb.addItem(jtf.getText());  //增加数据
                    panel.add(showInfo);
                    showInfo.setText("增加成功，新增了：" + jtf.getText());
                }
                else
                {
                    panel.add(showInfo);
                    showInfo.setText("请输入要添加星座");
                }
            }
        });

        buttonDel.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String commend = e.getActionCommand();
                if(cmb.getSelectedIndex() != -1)
                {
                    //先要获得要删除的项的数据
                    String strDel = cmb.getSelectedItem().toString();
                    cmb.removeItem(strDel);
                    panel.add(showInfo);
                    showInfo.setText("删除成功，删除了：" + strDel);
                }
                else
                {
                    panel.add(showInfo);
                    showInfo.setText("请选择要删除的星座");
                }
            }
        });

        cmb.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                String str = e.getItem().toString();
                panel.add(showInfo);
                showInfo.setText("您选择的星座是: " + str);
            }
        });

        frame.setBounds(300,200,600,200);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }


    public static void main(String[] args) {
        new SampeDemo();
    }
}
